package com.bawei.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.domain.MallProductBrandLove;
import com.bawei.mall.product.mapper.MallProductBrandLoveMapper;
import com.bawei.mall.product.service.MallProductBrandLoveService;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.system.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author：HaoYunde
 * @Package：com.bawei.mall.product.service.impl
 * @Project：mall_cloud
 * @name：MallProductBrandLoveServiceImpl
 * @Date：2024/6/29 10:47
 */
@Service
public class MallProductBrandLoveServiceImpl implements MallProductBrandLoveService {
    @Autowired
    private MallProductBrandLoveMapper mapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String ACCESS_TOKEN="login_tokens:";


    @Override
    public void add(MallProductBrandLove mallProductBrandLove) {
        //获取登录人id
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String o = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSON.parseObject(o, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();
        mallProductBrandLove.setUserId(Integer.valueOf(String.valueOf(cusUser.getUserId())));
        //获取登录人id
        //Long userId = SecurityUtils.getUserId();
        //品牌id
        Integer brandId = mallProductBrandLove.getBrandId();
        //判断是否存在
        MallProductBrandLove mall=mapper.selectList(brandId,userId);
        if(mall!=null){
            throw new RuntimeException("已经收藏");
        }
        mapper.add(mallProductBrandLove);
    }

    private String getTokenKey(String key)
    {
        return ACCESS_TOKEN + key;
    }

    @Override
    public void del(Integer id) {
        //获取登录人id
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String o = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSON.parseObject(o, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();
        mapper.del(id,userId);
    }
}
